package com.zs4sdk.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.zs4sdk.common.Extra;
import com.common.library.util.ActivityHelper;
import com.common.library.util.FileUtils;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;

import org.wlf.filedownloader.DownloadFileInfo;
import org.wlf.filedownloader.FileDownloadConfiguration;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.listener.OnDeleteDownloadFileListener;
import org.wlf.filedownloader.listener.OnDownloadFileChangeListener;
import org.wlf.filedownloader.listener.OnFileDownloadStatusListener;
import org.wlf.filedownloader.listener.simple.OnSimpleFileDownloadStatusListener;

import java.io.File;
import java.io.IOException;

/**
 * Created by jancy on 2017/2/6.
 */

public class Zs4GameDownloadApkActivity extends Zs4GameBaseActivity {

    public static final String TAG = Zs4GameVoucherResultActivity.class.getSimpleName();

    TextView mTitleView;
    TextView mDescView;
    Button mDownloadResultButton;
    ProgressBar mProgressBar;
    boolean isCanClosed = false;
    boolean isFix = false;

    String url = "";
    String path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_download_apk"));
//        path = FileUtils.getInternalCacheDir();
        setPathWEX(FileUtils.getInternalCacheDir());
        path = FileUtils.getInternalCacheDir().concat("sdkapk");
        doinitFileDownload();
        init();
        getParams();
    }

    private void doinitFileDownload() {
        // 1、创建Builder
        FileDownloadConfiguration.Builder builder = new FileDownloadConfiguration.Builder(this);

// 2.配置Builder
// 配置下载文件保存的文件夹
        builder.configFileDownloadDir(path);
// 配置同时下载任务数量，如果不配置默认为2
        builder.configDownloadTaskSize(3);
// 配置失败时尝试重试的次数，如果不配置默认为0不尝试
        builder.configRetryDownloadTimes(2);
// 开启调试模式，方便查看日志等调试相关，如果不配置默认不开启
//        builder.configDebugMode(false);
// 配置连接网络超时时间，如果不配置默认为15秒
        builder.configConnectTimeout(25000);// 25秒

// 3、使用配置文件初始化FileDownloader
        FileDownloadConfiguration configuration = builder.build();
        FileDownloader.init(configuration);
        FileDownloader.registerDownloadStatusListener(mOnFileDownloadStatusListener);
        FileDownloader.registerDownloadFileChangeListener(mOnDownloadFileChangeListener);

    }

    private void getParams() {
        Intent intent = getIntent();
        if (Helper.isNotNull(intent)) {
            if (intent.hasExtra(Extra.INTENTKEY.TITLE)) {
                mTitleView.setText(intent.getStringExtra(Extra.INTENTKEY.TITLE));
            }
            if (intent.hasExtra(Extra.INTENTKEY.INTENT_TYPE)) {
                isCanClosed = intent.getBooleanExtra(Extra.INTENTKEY.INTENT_TYPE, false);
            }
            if (intent.hasExtra(Extra.INTENTKEY.URL)) {
                url = intent.getStringExtra(Extra.INTENTKEY.URL);
                if (Helper.isNull(url) || Helper.isEmpty(url)) {
                    setbutton("下载链接错误，请联系客服！", false, "无法下载");
                }
            }
        }
        FileDownloader.start(url);
    }


    protected void init() {
        initReferences();
    }


    private void initReferences() {

        LogUtil.e("ping====", this.mScreenOrientation + "");

        mTitleView = (TextView) findViewById(ActivityHelper.getIdResId("zs4gameviewid_mTitleView_view_download_result"));
        mDescView = (TextView) findViewById(ActivityHelper.getIdResId("zs4gameviewid_view_download_result_desc"));
        mDownloadResultButton = (Button) findViewById(ActivityHelper.getIdResId("zs4gameviewid_btn_download_result_goto_game"));
        mProgressBar = (ProgressBar) findViewById(ActivityHelper.getIdResId("zs4gameviewid_pgb_download"));

        setViewClickEvent(this, ActivityHelper.getIdResId("zs4gameviewid_btn_download_result_goto_game"));

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (ActivityHelper.getIdResId("zs4gameviewid_btn_download_result_goto_game") == id) {
//            if (isFix) {
//                FileDownloader.pauseAll();// 暂停所有下载任务
//            } else {
            FileDownloader.start(url);// 继续下载，自动会断点续传（如果服务器无法支持断点续传将从头开始下载）
//            }
        }
    }


    // 不能后退
    @Override
    public void onBackPressed() {
//        finish();
    }

    private void setbutton(String content, boolean enable, String btnText) {

        mDescView.setText(content);
        mDownloadResultButton.setEnabled(enable);
        mDownloadResultButton.setText(btnText);
        if (!enable) {
            mDownloadResultButton.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gameicon_btn_get_verify_again_bg"));
        } else {
            mDownloadResultButton.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_red_5_bg"));
        }
    }

    private OnFileDownloadStatusListener mOnFileDownloadStatusListener = new OnSimpleFileDownloadStatusListener() {
        @Override
        public void onFileDownloadStatusRetrying(DownloadFileInfo downloadFileInfo, int retryTimes) {
            // 正在重试下载（如果你配置了重试次数，当一旦下载失败时会尝试重试下载），retryTimes是当前第几次重试
            setbutton("正在重试下载", false, "正在重试下载...");
            isFix = false;
//            mDownloadResultButton.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gameicon_btn_get_verify_again_bg"));
        }

        @Override
        public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
            // 等待下载（等待其它任务执行完成，或者FileDownloader在忙别的操作）
            setbutton("正在等待下载", false, "正在等待下载...");
            isFix = false;
        }

        @Override
        public void onFileDownloadStatusPreparing(DownloadFileInfo downloadFileInfo) {
            // 准备中（即，正在连接资源）
            setbutton("正在连接资源", false, "准备中...");
            isFix = false;
        }

        @Override
        public void onFileDownloadStatusPrepared(DownloadFileInfo downloadFileInfo) {
            // 已准备好（即，已经连接到了资源）
            setbutton("已经连接到了资源", false, "准备下载...");
            isFix = false;
        }

        @Override
        public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo, float downloadSpeed, long
                remainingTime) {
            // 正在下载，downloadSpeed为当前下载速度，单位KB/s，remainingTime为预估的剩余时间，单位秒
            double downloadSize = downloadFileInfo.getDownloadedSizeLong() / 1024f / 1024f;
            double fileSize = downloadFileInfo.getFileSizeLong() / 1024f / 1024f;
            int progressNum = (int) (100 * ((float) (Math.round(downloadSize * 100)) / 100) / ((float) (Math.round(fileSize * 100)) / 100));
            mProgressBar.setProgress(progressNum);
            int progressSecNum = (int) (100 * downloadSpeed / 1024f / ((float) (Math.round(fileSize * 100)) / 100)) + 1;
            mProgressBar.setSecondaryProgress(progressNum + progressSecNum);

            String desc = progressNum + "%   " + ((float) (Math.round(downloadSize * 100)) / 100) + "M/"
                    + ((float) (Math.round(fileSize * 100)) / 100) + "M    "
                    + downloadSpeed + "KB/s";
            setbutton(desc, false, "正在下载...");
            isFix = false;
        }

        @Override
        public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
            // 下载已被暂停
            setbutton("下载已暂停", true, "继续下载...");
            isFix = false;
        }

        @Override
        public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
            // 下载完成（整个文件已经全部下载完成）

            String apk = downloadFileInfo.getFilePath();
            setPathWEX(path);
            setPathWEX(apk);
            mProgressBar.setProgress(100);
            setbutton("已下载完成", true, "安装");
            File f = new File(apk);
            if (f.exists()) {
                FileUtils.openFile(f, Zs4GameDownloadApkActivity.this);
                isFix = true;
                if (isCanClosed) {
                    finish();
                }
            } else {
                FileDownloader.delete(url, true, mOnDeleteDownloadFileListener);
            }
        }

        @Override
        public void onFileDownloadStatusFailed(String url, DownloadFileInfo downloadFileInfo, FileDownloadStatusFailReason failReason) {
            // 下载失败了，详细查看失败原因failReason，有些失败原因你可能必须关心

            String failType = failReason.getType();
            String failUrl = failReason.getUrl();// 或：failUrl = url，url和failReason.getType()会是一样的

            setbutton("下载出错！", true, "点击继续下载");
            if (FileDownloadStatusFailReason.TYPE_URL_ILLEGAL.equals(failType)) {
                // 下载failUrl时出现url错误
                mDescView.setText("下载地址出错...");
            } else if (FileDownloadStatusFailReason.TYPE_STORAGE_SPACE_IS_FULL.equals(failType)) {
                // 下载failUrl时出现本地存储空间不足
                mDescView.setText("本地存储空间不足...");
            } else if (FileDownloadStatusFailReason.TYPE_NETWORK_DENIED.equals(failType)) {
                // 下载failUrl时出现无法访问网络
                mDescView.setText("无法访问网络...");
            } else if (FileDownloadStatusFailReason.TYPE_NETWORK_TIMEOUT.equals(failType)) {
                // 下载failUrl时出现连接超时4165654
                mDescView.setText("连接超时...");
            } else {
                // 更多错误....
            }

            // 查看详细异常信息
            Throwable failCause = failReason.getCause();// 或：failReason.getOriginalCause()

            // 查看异常描述信息
            String failMsg = failReason.getMessage();// 或：failReason.getOriginalCause().getMessage()
            ActivityHelper.showToast(url + failMsg);
            isFix = false;
        }
    };


    private OnDownloadFileChangeListener mOnDownloadFileChangeListener = new OnDownloadFileChangeListener() {
        @Override
        public void onDownloadFileCreated(DownloadFileInfo downloadFileInfo) {
            // 一个新下载文件被创建，也许你需要同步你自己的数据存储，比如在你的业务数据库中增加一条记录

        }

        @Override
        public void onDownloadFileUpdated(DownloadFileInfo downloadFileInfo, Type type) {
            // 一个下载文件被更新，也许你需要同步你自己的数据存储，比如在你的业务数据库中更新一条记录
        }

        @Override
        public void onDownloadFileDeleted(DownloadFileInfo downloadFileInfo) {
            // 一个下载文件被删除，也许你需要同步你自己的数据存储，比如在你的业务数据库中删除一条记录
//            FileDownloader.delete(url, true, mOnDeleteDownloadFileListener);
        }
    };


    private OnDeleteDownloadFileListener mOnDeleteDownloadFileListener = new OnDeleteDownloadFileListener() {
        @Override
        public void onDeleteDownloadFileFailed(DownloadFileInfo downloadFileInfo, DeleteDownloadFileFailReason deleteDownloadFileFailReason) {
            FileDownloader.start(url);
            Log.e("000000000000000000003", deleteDownloadFileFailReason.toString());
        }

        @Override
        public void onDeleteDownloadFilePrepared(DownloadFileInfo downloadFileInfo) {
            Log.e("000000000000000000004", "准备删除中。。。");
        }

        @Override
        public void onDeleteDownloadFileSuccess(DownloadFileInfo downloadFileInfo) {
            FileDownloader.start(url);
            Log.e("000000000000000000005", "删除成功。。。");
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileDownloader.unregisterDownloadStatusListener(mOnFileDownloadStatusListener);
        FileDownloader.unregisterDownloadFileChangeListener(mOnDownloadFileChangeListener);
    }

    /**
     * 下载apk路径权限授权
     *
     * @param path
     */
    private void setPathWEX(String path) {
        String[] command = {"chmod", "755", path};
        ProcessBuilder builder = new ProcessBuilder(command);
        try {
            builder.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
